﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Defect_Tracking_System.Models;

namespace Defect_Tracking_System.Controllers
{
    public class GroupController : Controller
    {
        //
        // GET: /Group/
        GroupManagement GroupManager = new GroupManagement();
        [Authorize(Roles="System Admin")]
        public ActionResult Index(int PageIndex = 1, string keyWord = "Search Group", string returnType = "View")
        {
            keyWord = String.IsNullOrEmpty(keyWord) ? "Search Group" : keyWord;
            GroupListModel model = new GroupListModel(keyWord, PageIndex);
            if (returnType.ToLower() == "view")
            {
                return View(model);
            }
            else
            {
                return Json(model);
            }
        }

        [Authorize(Roles = "System Admin")]
        public ActionResult EnableDisableGroup(string id, string act, int pageIndex, string keyWord)
        {
            try
            {
                GroupManager.EnableDisableGroup(id, act);
                return RedirectToAction("Index", new { PageIndex = pageIndex, keyWord = keyWord });
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                return View("Error");
            }
        }

        [Authorize(Roles = "System Admin")]
        public ActionResult DeleteGroup(string id, int pageIndex, string keyWord)
        {
            try
            {
                GroupManager.DeleteGroup(id);
                return RedirectToAction("Index", new { PageIndex = pageIndex, keyWord = keyWord });
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                return View("Error");
            }
        }

        [Authorize(Roles="System Admin"), HttpPost]
        public ActionResult DeleteGroup(int PageIndex, string keyWord, FormCollection form)
        {
            try
            {
                string groups = form["GroupId"];
                if (groups != null)
                {
                    char[] splitChar = { ',' };
                    string[] groupIds = groups.Split(splitChar);
                    foreach (string groupId in groupIds)
                    {
                        GroupManager.DeleteGroup(groupId);
                    }
                }
                return RedirectToAction("Index", new { PageIndex = PageIndex, keyWord = keyWord });
            }
            catch (Exception ex)
            {
                ViewData["message"] = ex.Message;
                return View("Error");
            }
        }
    }
}